﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.Web;
using ResourceBlender.DAL;
using ResourceBlender.Core;

public partial class ResourcesOffline : LocalPage {
    private Database db = new Database();

    /// <summary>
    /// Datebinds the application CheckBoxList
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e) {
        lblError.Visible = false;
        if(!Page.IsPostBack) {
            litAddAppLink.Text = ASPNETUtils.FormatLink(I18nUtils.GetString("UIStrings", "AddAppLink"), ResolveUrl("~/Applications.aspx"));
            litPageDescription.Text = ASPNETUtils.FormatLink(I18nUtils.GetString("UIStrings", "ExportWikiLink"), "http://wiki.lime49.com/index.php?title=Editing_RBT_Files");
            using(Command cmd = db.CreateCommand()) {
            /*    cmd.CommandText = "SELECT id, displayname FROM " + db.TablePrefix + "applications ORDER BY name ASC";
                Database.DataAdapter adapter = new Database.DataAdapter(cmd);
                DataSet ds = new DataSet();
                adapter.Fill(ds);
                chlApplication.DataSource = ds;
                chlApplication.DataValueField = "id";
                chlApplication.DataTextField = "displayname";*/
                chlApplication.DataBind();
                if(chlApplication.Items.Count > 0) {
                    ShowLanguages(null, EventArgs.Empty);
                    mltMain.ActiveViewIndex = 1;
                }
            }
            Page.ClientScript.RegisterStartupScript(typeof(Page), "postbackfix", @"
                var __oldAction = theForm.action;
                var __oldPostBack = __doPostBack;
                __doPostBack = function(eventTarget, eventArgument) {
                    theForm.action = __oldAction;
                    __oldPostBack(eventTarget, eventArgument);            
                };", true);
        }
        ScriptManager.RegisterStartupScript(this, typeof(Page), "nojs", "$(function(){ $('#" + btnRefresh.ClientID + "').remove(); });", true);
    }

    /// <summary>
    /// Shows the languages and bundles for the application selected.
    /// </summary>
    /// <param name="sender">The sender.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void ShowLanguages(object sender, EventArgs e) {
        lstLanguages.Items.Clear();
        lstBundles.Items.Clear();
        if(string.IsNullOrEmpty(chlApplication.SelectedValue)) {
            return;
        }
        List<string> appIds = new List<string>();
        foreach(ListItem itm in chlApplication.Items) {
            if(itm.Selected) {
                appIds.Add(itm.Value);
            }
        }
        List<RBApplication> applications = ResourceBlenderDAL.GetApplications(appIds.ToArray(), true);
        ListComparer cmp = new ListComparer();
        List<string> languages = new List<string>();
        List<ListItem> tempLanguages = new List<ListItem>(),
                       tempBundles = new List<ListItem>();
        foreach(RBApplication app in applications) {
            foreach(string lang in app.Languages) {
                if(!languages.Contains(lang)) {
                    ListItem itm = new ListItem(Utils.GetSafeEnglishName(lang), lang);
                    itm.Selected = true;
                    tempLanguages.Add(itm);
                    languages.Add(lang);
                }
            }
            foreach(KeyValuePair<string,string> bundle in app.Bundles) {
                ListItem itmBundle = new ListItem(bundle.Value, bundle.Key);
                itmBundle.Selected = true;
                tempBundles.Add(itmBundle);
            }
        }
        string[] langs;
        
        tempLanguages.Sort(cmp);
        lstLanguages.Items.AddRange(tempLanguages.ToArray());
        if(lstLanguages.Items.Count == 0) {
            ListItem itm = new ListItem(I18nUtils.GetString("UIStrings", "NoLanguagesFound"), "");
            itm.Selected = true;
            lstLanguages.Items.Add(itm);
            lstLanguages.Enabled = false;
        } else {
            lstLanguages.Enabled = true;
        }

        tempBundles.Sort(cmp);
        lstBundles.Items.AddRange(tempBundles.ToArray());
        if(lstBundles.Items.Count == 0) {
            ListItem itm = new ListItem(I18nUtils.GetString("UIStrings", "NoBundlesFound"), "");
            itm.Selected = true;
            lstBundles.Items.Add(itm);
            lstBundles.Enabled = false;
        } else {
            lstBundles.Enabled = true;
        }
    }

    /// <summary>
    /// Exports to an RBT translation database or XML spreadsheet.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Export(object sender, EventArgs e) {
        List<string> applicationIds = new List<string>();
        if(chlApplication != null) {
            foreach(ListItem itm in chlApplication.Items) {
                if(itm.Selected && itm.Value.Length > 0) {
                    applicationIds.Add(itm.Value);
                }
            }
        }
        if(applicationIds.Count == 0) {
            lblError.Visible = true;
            lblError.Text = I18nUtils.GetString("Errors", "ApplicationNotSpecified");
        }
        List<string> bundles = new List<string>();
        List<string> selectedLanguages = new List<string>();
        foreach(ListItem itm in lstLanguages.Items) {
            if(itm.Selected && itm.Value.Length > 0) {
                selectedLanguages.Add(itm.Value);
            }
        }
        foreach(ListItem itm in lstBundles.Items) {
            if(itm.Selected && itm.Value.Length > 0) {
                bundles.Add(itm.Value);
            }
        }
        try {
            switch((sender as Button).CommandArgument) {
                case "rbt":
                    ResourceGenerator.ExportToRBT(null, applicationIds.ToArray(), selectedLanguages.ToArray(), bundles.ToArray(), chkZip.Checked);
                    break;
                case "xls":
                    ResourceGenerator.ExportToExcel(applicationIds.ToArray(), selectedLanguages.ToArray(), bundles.ToArray(), chkZip.Checked);
                    break;
            }
        } catch(Exception ex) {
            lblError.Visible = true;
            lblError.Text = ex.Message;
        }
    }
}
